package fr.umlv.escape_ig.ship;

import fr.umlv.escape_ig.R;
import fr.umlv.escape_ig.sprite.Sprite;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;

public class Robot extends Sprite {

        private final static float ROBOT_SIZE = 50.0f;
        
        private final static float SPEED = 5.0f;

        private float destX;
        private float destY;
        
        private boolean isArrived = true;

        private final Object lock = new Object();

        private final Bitmap image;
        
        public Robot(Context context) {
                this(context, 200.0f, 150.0f);
        }
        
        public Robot(Context context, float left, float top) {
                super(left, top, left+ROBOT_SIZE, top+ROBOT_SIZE);
                this.image = BitmapFactory.decodeResource(context.getResources(), R.drawable.ship);
        }

        public void moveTo(float x, float y) {
                synchronized (lock) {
                        isArrived = false;
                        this.destX = x;
                        this.destY = y;
                }
        }

        @Override
        public void draw(Canvas canvas) {
                synchronized (lock) {
                        canvas.drawBitmap(image, null, rect, null);
                }
        }

        public void update() {
                synchronized (lock) {
                        if (isArrived) {
                                return;
                        }
                        
                        float dx = destX - rect.centerX();
                        float dy = destY - rect.centerY();

                        float d = dx*dx + dy*dy;
                        
                        // Stop moving when we are 5 pixels away from the destination
                        if (d < 25) { 
                                isArrived = true;
                        }               

                        float sqrtD = (float) Math.sqrt(d);             
                        
                        float x = SPEED*(dx / sqrtD);
                        float y = SPEED*(dy / sqrtD);
                        move(x, y);                     
                }
        }
}